/**
 * 
 */
package com.yinhai.activity;

import android.app.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.LayoutParams;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.yinhai.adapter.MSGListAdapter;
import com.yinhai.constant.Contact;
import com.yinhai.model.SMSBean;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.service.SMSServiceImpl;
import com.yinhai.util.ManagerContact;
import com.yinhai.util.NullUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Juyon
 * 
 */
public class MsgFragment extends Fragment {
    
    private SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
    private SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月dd日");
    
    private MSGListAdapter adapter;
    
    // private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    private int currentTopPageNo = 0, totalPage = 0;
    
    private Context context;
    
    private AQuery aq;
    
    private int lastIndex = 0, sumCount = 0;
    
    // View view =null;
    private boolean isLoading = false;
    
    private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
    
    private PopupWindow mPdw_nav;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_msg, null);
        aq = new AQuery(getActivity(), view);
        
        aq.id(R.id.common_ad).gone();
        
        try {
            
            context = this.getActivity();
            
//            aq.id(R.id.msg_radio_im).clicked(new OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//
//                    FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
//                    Fragment fragment = FragmentFactory.getInstance().getInstanceById(R.id.radio_msg);
//                    transaction.replace(R.id.container, fragment);
//                    transaction.commit();
//                }
//            });
            
            currentTopPageNo = 1;
            // currentBottomPageNo = 0;
            sumCount = new SMSServiceImpl(getActivity()).findThreadCount();
            
            totalPage = sumCount / Contact.LIMIT;
            if (sumCount % Contact.LIMIT != 0) {
                totalPage += 1;
            }
            
            isLoading = true;
            adapter = new MSGListAdapter(getActivity(), data) {
                
                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    final View view = super.getView(position, convertView, parent);
                    ImageView imageView = (ImageView)view.findViewById(R.id.img);
                    imageView.setTag(data.get(position));
                    imageView.setClickable(true);
                    imageView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View arg0) {
                            Map<String, Object> item = (Map<String, Object>)arg0.getTag();
                            showPopWin(view, item);
                        }
                    });
                    return view;
                }
                
            };
            // aq.id(R.id.msg_lst1).
            aq.id(R.id.msg_lst1).adapter(adapter).itemClicked(OnItemClick);
            // .scrolled(listScrolled);
            aq.id(R.id.msg_lst1).getListView().setOnItemLongClickListener(OnItemLongclick);
            
            findMsgData(0);
            
            // 点击弹出框，还是跳转到编辑短信页面
            view.findViewById(R.id.btn_add).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        Intent intent = new Intent(getActivity(), SMSDetailActivity.class);
                        intent.putExtra("flag", "add");
                        startActivity(intent);
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.im.message");
            getActivity().registerReceiver(receiver, intentFilter);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }
    
    private void showPopWin(View view, final Map<String, Object> data) {
        final String phoneNum = data.get("address").toString().replace("+86", "");
        View popView = LayoutInflater.from(getActivity()).inflate(R.layout.dial_nav, null);
        mPdw_nav = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        
        TextView navCall = (TextView)popView.findViewById(R.id.dial_nav_call);
        navCall.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                Uri uri = Uri.parse("tel:" + data.get("address").toString().replace("+86", ""));
                Intent call = new Intent(Intent.ACTION_CALL, uri);
                getActivity().startActivity(call);
                if (mPdw_nav != null && mPdw_nav.isShowing()) {
                    mPdw_nav.dismiss();
                }
            }
        });
        TextView navMsg = (TextView)popView.findViewById(R.id.dial_nav_msg);
        navMsg.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                Intent in = new Intent(getActivity(), SMSDetailActivity.class);
                in.putExtra("threadId", data.get("threadId").toString());
                in.putExtra("address", data.get("address").toString());
                startActivity(in);
                if (mPdw_nav != null && mPdw_nav.isShowing()) {
                    mPdw_nav.dismiss();
                }
            }
        });
        
        TextView dial_nav_record = (TextView)popView.findViewById(R.id.dial_nav_detail);
        Drawable drawable = getActivity().getResources().getDrawable(R.drawable.pop_3);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        dial_nav_record.setCompoundDrawables(null, drawable, null, null);
        dial_nav_record.setText(Contact.TEXT_NAME_ADD);
        
        if (ManagerContact.getContactPeople(getActivity(), phoneNum)) {
            dial_nav_record.setText(Contact.TEXT_NAME_ADD);
            dial_nav_record.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View arg0) {
                    Intent mainIntent = new Intent(getActivity(), LocalContactAddActivity.class);
                    mainIntent.putExtra("phone", phoneNum);
                    getActivity().startActivity(mainIntent);
                    if (mPdw_nav != null && mPdw_nav.isShowing()) {
                        mPdw_nav.dismiss();
                    }
                }
            });
        } else {
            dial_nav_record.setText(Contact.TEXT_NAME_DETAIL);
            dial_nav_record.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View arg0) {
                    Intent mainIntent = new Intent(getActivity(), LocalContactAddActivity.class);
                    mainIntent.putExtra("phone", phoneNum);
                    mainIntent.putExtra("pagetype", 1);
                    getActivity().startActivity(mainIntent);
                    if (mPdw_nav != null && mPdw_nav.isShowing()) {
                        mPdw_nav.dismiss();
                    }
                }
            });
        }
        TextView dial_nav_detail = (TextView)popView.findViewById(R.id.dial_nav_detail);
        drawable = getActivity().getResources().getDrawable(R.drawable.pop_3);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        dial_nav_detail.setCompoundDrawables(null, drawable, null, null);
        dial_nav_detail.setText("删除");
        dial_nav_detail.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                String thread = data.get("threadId").toString();
                int i =
                    getActivity().getContentResolver().delete(Uri.parse("content://sms/conversations/" + thread),
                        null,
                        null);
                if (i == 0) {
                    int j =
                        getActivity().getContentResolver()
                            .delete(Uri.parse("content://mms-sms/conversations/" + thread), null, null);
                    if (j > 0) {
                        adapter.delMap(data);
                        adapter.notifyDataSetChanged();
                        Toast.makeText(getActivity(), "短信删除成功", Toast.LENGTH_SHORT).show();
                        
                    }
                }
                if (i > 0) {
                    adapter.delMap(data);
                    adapter.notifyDataSetChanged();
                    Toast.makeText(getActivity(), "短信删除成功", Toast.LENGTH_SHORT).show();
                }
                if (mPdw_nav != null && mPdw_nav.isShowing()) {
                    mPdw_nav.dismiss();
                }
            }
        });
        // 点击弹出层外自动消失
        mPdw_nav.setBackgroundDrawable(this.getActivity().getResources().getDrawable(R.drawable.dial_dialog_bgup));
        mPdw_nav.setOutsideTouchable(true);
        mPdw_nav.showAsDropDown(view);
        
    }
    
    OnItemClickListener OnItemClick = new OnItemClickListener() {
        
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            try {
                
                // 获取传入的数据
                Map<String, Object> valMap = (Map<String, Object>)adapter.getItem(arg2);
                String threadId = valMap.get("threadId") == null ? "" : valMap.get("threadId").toString();
                if (!"".equals(threadId)) {
                    Intent intent = new Intent(getActivity(), SMSDetailActivity.class);
                    intent.putExtra("threadId", threadId);
                    intent.putExtra("address", valMap.get("address").toString());
                    intent.putExtra("displayName", valMap.get("displayName").toString());
                    startActivity(intent);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
    };
    
    OnItemLongClickListener OnItemLongclick = new OnItemLongClickListener() {
        
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            try {
                
                // 获取传入的数据
                final Map<String, Object> valMap = (Map<String, Object>)adapter.getItem(arg2);
                
                // Juyon
                if (valMap.get("address") != null) {
                    final String phoneNum = valMap.get("address").toString().replace("+86", "");
                    String[] str = null;
                    final boolean phoneIsInContact =
                        ManagerContact.getContactPeople(MsgFragment.this.getActivity(), phoneNum);
                    if (phoneIsInContact) {
                        // 通讯录不存在该号码，则新增
                        str = new String[] {"新增", "呼叫", "回复", "删除"};
                    } else {
                        
                        // 通讯录中存在该号码，则查看
                        str = new String[] {"查看", "呼叫", "回复", "删除"};
                    }
                    
                    new AlertDialog.Builder(getActivity()).setTitle("信息选项")
                        .setItems(str, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        if (phoneIsInContact) {
                                            // Juyon:未在通讯录中，则新增联系人信息
                                            Intent mainIntent =
                                                new Intent(getActivity(), LocalContactAddActivity.class);
                                            mainIntent.putExtra("phone", phoneNum);
                                            getActivity().startActivity(mainIntent);
                                        } else {
                                            // Juyon:在通讯录中，查看联系人信息
                                            Intent mainIntent =
                                                new Intent(getActivity(), LocalContactAddActivity.class);
                                            mainIntent.putExtra("phone", phoneNum);
                                            mainIntent.putExtra("pagetype", 1);
                                            getActivity().startActivity(mainIntent);
                                        }
                                        break;
                                    case 1:
                                        Uri uri =
                                            Uri.parse("tel:" + valMap.get("address").toString().replace("+86", ""));
                                        Intent call = new Intent(Intent.ACTION_CALL, uri);
                                        getActivity().startActivity(call);
                                        break;
                                    case 2:
                                        Intent in = new Intent(getActivity(), SMSDetailActivity.class);
                                        in.putExtra("threadId", valMap.get("threadId").toString());
                                        in.putExtra("address", valMap.get("address").toString());
                                        startActivity(in);
                                        break;
                                    case 3:
                                        String thread = valMap.get("threadId").toString();
                                        int i =
                                            getActivity().getContentResolver()
                                                .delete(Uri.parse("content://sms/conversations/" + thread), null, null);
                                        if (i == 0) {
                                            int j =
                                                getActivity().getContentResolver()
                                                    .delete(Uri.parse("content://mms-sms/conversations/" + thread),
                                                        null,
                                                        null);
                                            if (j > 0) {
                                                adapter.delMap(valMap);
                                                adapter.notifyDataSetChanged();
                                                Toast.makeText(getActivity(), "短信删除成功", Toast.LENGTH_SHORT).show();
                                                
                                            }
                                        }
                                        if (i > 0) {
                                            adapter.delMap(valMap);
                                            adapter.notifyDataSetChanged();
                                            Toast.makeText(getActivity(), "短信删除成功", Toast.LENGTH_SHORT).show();
                                        }
                                        break;
                                }
                            }
                        })
                        .show();
                    
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            return false;
        }
        
    };
    
    private class MyAsyncQueryHandler extends AsyncQueryHandler {
        
        public MyAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }
        
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            Cursor cursorPhone = null;
            Date nowDate = null;
            try {
                if (cursor == null) {
                    return;
                }
                
                try {
                    nowDate = dateTimeFormat.parse(dateFormat.format(new Date()) + " 23:59:59");
                } catch (ParseException e) {
                    nowDate = new Date();
                }
                data.clear();
                List<SMSBean> beans = new ArrayList<SMSBean>();
                for (int i = 0; i < cursor.getCount(); i++) {
                    cursor.moveToPosition(i);
                    SMSBean mmt =
                        new SMSBean(cursor.getString(0), cursor.getString(1), cursor.getString(2), cursor.getLong(3),
                            cursor.getString(4));
                    String snippet_cs = cursor.getString(5);
                    if (NullUtils.isEmpty(mmt.getMsg_snippet())) {
                        mmt.setMsg_snippet("无主题");
                    }
                    if (NullUtils.isNotEmpty(snippet_cs) && snippet_cs.equals("106")) {
                        if (null != mmt.getMsg_snippet()) {
                            mmt.setMsg_snippet(new String(mmt.getMsg_snippet().getBytes("ISO8859_1"), "utf-8"));
                        }
                    }
                    
                    beans.add(mmt);
                    
                }
                cursor.close();
                String recipientIds = "";
                Map<String, SMSBean> map = new HashMap<String, SMSBean>();
                for (int i = 0; i < beans.size(); i++) {
                    SMSBean temp = beans.get(i);
                    
                    map.put(temp.getRecipient_id(), temp);
                    
                    if (recipientIds.equals("")) {
                        recipientIds = temp.getRecipient_id();
                    } else {
                        recipientIds += "," + temp.getRecipient_id();
                    }
                    if (i == beans.size() - 1 || map.size() >= 100) {
                        cursorPhone =
                            context.getContentResolver().query(Uri.parse("content://mms-sms/canonical-addresses"),
                                new String[] {"_id", "address"},
                                " _id in (" + recipientIds + ")",
                                null,
                                null);
                        
                        for (int y = 0; y < cursorPhone.getCount(); y++) {
                            cursorPhone.moveToPosition(y);
                            SMSBean bean = map.get(cursorPhone.getString(0));
                            if (bean != null) {
                                bean.setName(cursorPhone.getString(1));
                                bean.setAddress(cursorPhone.getString(1));
                                if (ContactUserServiceImpl.phoneNames.get(bean.getAddress().replaceAll("\\+86", "")) != null) {
                                    bean.setName(ContactUserServiceImpl.phoneNames.get(bean.getAddress()
                                        .replaceAll("\\+86", "")));
                                }
                            }
                        }
                        
                        cursorPhone.close();
                        map.clear();
                        recipientIds = "";
                    }
                    // }
                }
                Calendar currentDate = Calendar.getInstance();
                GregorianCalendar date = new GregorianCalendar();
                for (SMSBean smsBean : beans) {
                    // 数据处理
                    Map<String, Object> bean = new HashMap<String, Object>();
                    bean.put("img", R.drawable.tel_photo);
                    bean.put("threadId", smsBean.getThread_id());
                    bean.put("name", smsBean.getName() + "(" + smsBean.getMsg_count() + ")");
                    bean.put("content", smsBean.getMsg_snippet());
                    bean.put("type", Contact.OLD_MSG);
                    bean.put("address", smsBean.getAddress());
                    bean.put("displayName", smsBean.getName());
                    
                    date.setTimeInMillis(smsBean.getDate());
                    if (currentDate.get(Calendar.YEAR) == date.get(Calendar.YEAR)) {
                        // 今天
                        if (nowDate.getTime() < (smsBean.getDate() + 24 * 60 * 60 * 1000L)) {
                            String hm =
                                date.get(Calendar.HOUR)
                                    + ":"
                                    + (date.get(Calendar.MINUTE) < 10 ? ("0" + date.get(Calendar.MINUTE))
                                        : date.get(Calendar.MINUTE));
                            bean.put("date", (date.get(Calendar.AM_PM) == 0 ? "上午" : "下午") + hm);
                        } else {
                            bean.put("date", dateFormat2.format(new Date(smsBean.getDate())));
                        }
                    } else {
                        bean.put("date", dateFormat.format(new Date(smsBean.getDate())));
                    }
                    // data.add(bean);
                    adapter.addMap(bean);
                }
                adapter.notifyDataSetChanged();
                isLoading = false;
                super.onQueryComplete(token, cookie, cursor);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                cursor.close();
            }
            
        }
        
    }
    
    private void findMsgData(int page) {
        isLoading = true;
        
        MyAsyncQueryHandler asyncQuery = new MyAsyncQueryHandler(context.getContentResolver());
        asyncQuery.startQuery(0, null, Uri.parse("content://mms-sms/conversations?simple=true"), new String[] {"_id",
            "message_count", "snippet", "date", "recipient_ids", "snippet_cs"}, null, null, " date desc--");
        
    }
    
    /**
     * 滚动翻页
     * */
    OnScrollListener listScrolled = new OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (lastIndex == sumCount && scrollState == SCROLL_STATE_IDLE) {
            }
        }
        
        @Override
        public void onScroll(AbsListView view, int first, int visible, int total) {
            lastIndex = first + visible;
            int footerCount = aq.id(R.id.msg_lst1).getListView().getFooterViewsCount();
            // Log.i("=====", "====first="+first + " visible =" + visible + "sumCount= " + sumCount +" footerCount ="
            // +footerCount) ;
            if (first + visible == total && sumCount > total - 1 - footerCount && !isLoading) {
                if (currentTopPageNo >= 1 && currentTopPageNo < totalPage) {
                    // Log.i("currentTopPageNo =", currentTopPageNo + "");
                    currentTopPageNo += 1;
                    findMsgData(currentTopPageNo);
                }
                
            }
        }
    };
    
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (intent.getAction().equals("com.im.message")) {
                    findMsgData(0);
                }
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    };
    
    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(receiver);
        super.onDestroy();
    }
    
}
